public class 换水问题II {
    
    public static void main(String[] args) {
        

    }

    public static int maxBottlesDrunk(int numBottles, int numExchange) {

        // 1、记交换空瓶次数为x
        int x = 0;
        // 2、记交换的总空瓶为cost，排列组合
        int cost = (0 + (x - 1)) * numExchange / 2;
        // 3、记产生的总空瓶为total
        int total = numBottles + x;

        /**
         * 则有不等式cost <= total
         * 问题转化为：求二元一次方程cost - total = 0的x根最大值
         * 代入得：x^2 + (2*numExchange - 3)*x - 2*numBottles = 0
         */
        // 4、使用求根公式。代入a * x^2 + b * x + c = 0中
        int a = 1;
        int b = 2 * numExchange - 3;
        int c = -2 * numBottles;
        x = (int) Math.ceil(((-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a)));
    
        return numBottles + x - 1;
    }
}
